package com.shanks.framework.mq.helper;

import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 辅助工具类
 */
@Component
public class MqHelper {
    private static final Logger logger = LoggerFactory.getLogger(MqHelper.class);

    @Resource
    private Environment environment;

    private static String mqInstanceName = null;


    public String getInstanceName() {
        if (StringUtils.isEmpty(mqInstanceName)) {
            // 从当前激活的环境变量读取
            mqInstanceName = environment.getProperty("rocketmq.client.instanceName");
            if (StringUtils.isEmpty(mqInstanceName)) {
                String servePort = environment.getProperty("server.port");
                if (StringUtils.isBlank(servePort)) {
                    logger.warn("无法获取消费者的实例名或者端口,请检查配置:{},或者 :{}", "rocketmq.client.instanceName", "server.port");
                } else {
                    try {
                        InetAddress localHost = InetAddress.getLocalHost();
                        String IP = localHost.getHostAddress();
                        mqInstanceName = IP + "@" + servePort;
                    } catch (UnknownHostException ex) {
                    }
                }
            }
        }
        return StringUtils.isEmpty(mqInstanceName) ? "UNNONE" : mqInstanceName;
    }
}
